package com.github.fork.config;

import org.springframework.web.WebApplicationInitializer;
import org.springframework.web.context.ContextLoaderListener;
import org.springframework.web.context.support.AnnotationConfigWebApplicationContext;
import org.springframework.web.filter.CharacterEncodingFilter;
import org.springframework.web.servlet.DispatcherServlet;

import javax.servlet.*;

import java.util.EnumSet;

/**
 * @author Jerry Liu
 * @since 2017/3/21
 */
public class ContainerInitializer implements WebApplicationInitializer {

    @Override
    public void onStartup(ServletContext container) throws ServletException {

        FilterRegistration.Dynamic filter = container.addFilter("encoding", new CharacterEncodingFilter());
        filter.addMappingForUrlPatterns(EnumSet.of(DispatcherType.REQUEST), true, "/");


        AnnotationConfigWebApplicationContext rootCtx = new AnnotationConfigWebApplicationContext();
        rootCtx.register(PropertiesConfig.class, ServiceConfig.class);

        container.addListener(new ContextLoaderListener(rootCtx));

        AnnotationConfigWebApplicationContext context = new AnnotationConfigWebApplicationContext();

        ServletRegistration.Dynamic servlet = container.addServlet("springmvc", new DispatcherServlet(context));
        servlet.setLoadOnStartup(1);
        servlet.addMapping("/*");

    }
}
